package com.bdqn.t320.aop;

import com.bdqn.t320.service.UserService;
import com.bdqn.t320.service.UserServiceImp;
import jdk.internal.org.objectweb.asm.tree.TryCatchBlockNode;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import sun.rmi.log.ReliableLog;

import java.util.Arrays;

public class UserServiceLogger {
    private static final Logger log = Logger.getLogger(UserServiceLogger.class);

    //前置增强  在调用我们实际要做的业务逻辑之前先执行
    public void before1111(JoinPoint jp) {
        log.info("前置增强:记录用户增加的service操作时间");
    }

    //后置增强
    public void afterReturning(JoinPoint joinPoint, Object result) {
        log.info("后置增强:调用" + joinPoint.getTarget() + "的"
                + joinPoint.getSignature().getName() + "方法。方法返回值:" + result);
    }

    //异常抛出增强
    public void afterTrowing(JoinPoint joinPoint, RuntimeException e) {
        log.info("异常抛出增强:" + joinPoint.getSignature().getName() + "方法发生异常:" + e);
    }

    //最终增强
    public void afterLogger(JoinPoint joinPoint) {
        log.info("最终增强:" + joinPoint.getSignature().getName() + "方法结束执行");
    }

    //环绕增强
    public Object aroundLogger(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("调用" + joinPoint.getTarget() + "的"
                + joinPoint.getSignature().getName() + "方法，方法入参:"
                + Arrays.toString(joinPoint.getArgs()));
        try {
            //执行目标方法并获得返回值
            Object result = joinPoint.proceed();//通过代理对象执行目标对象的方法
            //UserService userService = new UserServiceImp();
            //userService.saveService(new User());
            log.info("调用" + joinPoint.getTarget() + "的" + joinPoint.getSignature().getName() + "方法。方法返回值：" + result);
            return result;
        } catch (Throwable e) {
            log.error(joinPoint.getSignature().getName() + "方法发生异常:" + e);
            throw e;
        } finally {
            log.info(joinPoint.getSignature().getName() + "方法执行结束");
        }
    }
}
